#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import json
import socket
import struct
import subprocess

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 2007))
server.listen(1)

while True:
    conn, addr = server.accept()
    while True:
        command = conn.recv(1024)
        res = subprocess.Popen(command.decode("utf-8"), shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        stdout = res.stdout.read()
        stderr = res.stderr.read()
        header_dic = {
            "name": "a.txt",
            "total_size": len(stdout) + len(stderr)
        }
        header_str = json.dumps(header_dic)
        print(header_str, type(header_str))

        # 1、设置报头大小
        header_size = struct.pack("i", len(header_str))
        # 2、将报头发给客户端
        conn.send(header_size)
        conn.send(header_str.encode("utf-8"))
        # 发送字典
        conn.send(stdout)
        conn.send(stderr)

    conn.close()
